﻿
import tornado
import tornado.web

import os
import openai
import time
import requests
import jwt
import zhconv
import json
import method_stored
import datetime

sign_key ="lyb_test_2023"

class BaseHandler(tornado.web.RequestHandler):
    # blog.csdn.net/moshowgame 解决跨域问题
    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Max-Age', 3600)
        self.set_header('Content-type', 'application/json')
        self.set_header('Access-Control-Allow-Methods', 'POST, GET,DELETE,PUT')
        # self.set_header('Access-Control-Allow-Methods', '*')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE')
        # self.set_header("Access-Control-Allow-Origin", origin_url)
        # self.set_header("Access-Control-Allow-Credentials", "true")
        # 如果header中有多种信息请一定要加种headers，如果header中存在user-token，必须在下面加入user-token，即self.set_header("Access-Control-Allow-Headers", "x-requested-with,token,user-token")
        # self.set_header("Access-Control-Allow-Headers", "x-requested-with,token")

    def options(self):
        self.set_status(200)
        self.finish()




class login(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass


        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        phone=None
        api_key=None
        try:
            code = data["code"]
            run_result = method_stored.get_phone(code)
            # member =0
            if not code:
                result["msg"] = "code获取失败"
                return self.write(result)
            
            # print(code)
            if run_result!=None and type(run_result) ==dict and "phone_info" in run_result.keys():
                phone = run_result["phone_info"]["phoneNumber"]

            if not phone:
                result["msg"] = "手机号获取失败"
                return self.write(result)
            
            now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            #获取姓名
            nick_name,status,member = method_stored.phone_check(phone,now_time)
            result["data"]["nick_name"] = nick_name

            # 将 session_key 存储到数据结构中，并生成 JWT 令牌返回给客户端
            token = jwt.encode({'phone': phone,"now_time":now_time,"nick_name":nick_name}, sign_key, algorithm='HS256')

            result["data"]["token"] = str(token,"utf-8")
            result["data"]["phone"] = phone
            result["data"]["member"] = member
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)


class my_buy(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        # data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            #获取校验
            head = self.request.headers
            Authorization = head.get('Authorization', None)
            if type(Authorization) == list:
                Authorization = Authorization[0]
            msg,status,phone = method_stored.check_auth(Authorization)
            if not status:
                result["msg"] = msg
                return self.write(result)

            #获取手机号
            # phone = data["phone"]
            if not phone:
                result["msg"] = "手机号获取失败"
                return self.write(result)

            #获取购买的方法
            course_list,status = method_stored.get_my_buy(phone)
            

            result["data"]["courses"] = course_list

            # result["data"]["date"] = in_time
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)


#用户信息
class get_person_info(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            #获取校验
            head = self.request.headers
            Authorization = head.get('Authorization', None)
            if type(Authorization) == list:
                Authorization = Authorization[0]
            msg,status,phone = method_stored.check_auth(Authorization)
            if not status:
                result["msg"] = msg
                return self.write(result)


            #获取手机号
            # phone = data["phone"]
            if not phone:
                result["msg"] = "手机号获取失败"
                return self.write(result)

            # update_result,status = method_stored.update_person_info(data,str(phone))
            select_result,status = method_stored.person_info(phone)
            if "date" in select_result[0].keys():
                    select_result[0]["date"] = select_result[0]["date"].strftime('%Y-%m-%d')
            if status:
                result["data"]["date"] = select_result[0]
                msg="成功"
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                msg="获取失败"
                result["msg"] = msg

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)

#用户信息更新
class person_info_update(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            #获取校验
            head = self.request.headers
            Authorization = head.get('Authorization', None)
            if type(Authorization) == list:
                Authorization = Authorization[0]
            msg,status,phone = method_stored.check_auth(Authorization)
            if not status:
                result["msg"] = msg
                return self.write(result)


            #获取手机号
            # phone = data["phone"]
            if not phone:
                result["msg"] = "手机号获取失败"
                return self.write(result)

            update_result,status = method_stored.update_person_info(data,str(phone))
            if status:
                # result["data"]["date"] = in_time
                msg="成功"
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                msg="更新失败"
                result["msg"] = msg

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)


#用户信息
class get_person_card(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            #获取校验
            head = self.request.headers
            Authorization = head.get('Authorization', None)
            if type(Authorization) == list:
                Authorization = Authorization[0]
            msg,status,phone = method_stored.check_auth(Authorization)
            if not status:
                result["msg"] = msg
                return self.write(result)


            #获取手机号
            # phone = data["phone"]
            if not phone:
                result["msg"] = "手机号获取失败"
                return self.write(result)

            # update_result,status = method_stored.update_person_info(data,str(phone))
            select_result,status = method_stored.card_info(phone)
            if status:
                result["data"] = select_result[0]
                msg="成功"
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                msg="获取失败"
                result["msg"] = msg

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)

#用户信息更新
class person_card_update(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            #获取校验
            head = self.request.headers
            Authorization = head.get('Authorization', None)
            if type(Authorization) == list:
                Authorization = Authorization[0]
            msg,status,phone = method_stored.check_auth(Authorization)
            if not status:
                result["msg"] = msg
                return self.write(result)


            #获取手机号
            # phone = data["phone"]
            if not phone:
                result["msg"] = "手机号获取失败"
                return self.write(result)

            update_result,status = method_stored.update_person_card(data,str(phone))

            if status:
                # result["data"]["date"] = in_time
                msg="成功"
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                msg="更新失败"
                result["msg"] = msg

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)



#用户信息更新
class product_search(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            word =None
            page_id =0
            page_number =10

            
            if "word" in data.keys():
                word = data["word"]
            if "page_id" in data.keys():
                page_id = int(data["page_id"])
            if "page_number" in data.keys():
                page_number = int(data["page_number"])
            
            select_result = method_stored.get_course(word=word,page_id=page_id,page_number=page_number)
            for x in range(len(select_result)):
                if type(select_result[x]) ==dict and "date" in select_result[x].keys() and select_result[x]["date"]!=None:
                    select_result[x]["date"] = select_result[x]["date"].strftime('%Y-%m-%d')

            result["data"]["product_list"] = select_result
            result["data"]["page_id"] = page_id
            result["data"]["page_number"] = page_number
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)



#用户信息更新
class product_hot(BaseHandler):

    def get(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        # data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            
            select_result = method_stored.get_hot()
            result["data"]["product_list"] = select_result
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)


#用户信息更新
class chapter_search(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            word =None
            page_id =0
            page_number =10
            phone =None
            data ={}
            try:
                data = tornado.escape.json_decode(self.request.body)
            except Exception as e:
                pass
            try:
                #获取校验
                head = self.request.headers
                Authorization = head.get('Authorization', None)
                if type(Authorization) == list:
                    Authorization = Authorization[0]
                msg,status,phone = method_stored.check_auth(Authorization)
            except Exception as e:
                pass

            course_id = data["course_id"]
            #获取手机号
            if "word" in data.keys():
                word = data["word"]
            if "page_id" in data.keys():
                page_id = int(data["page_id"])
            if "page_number" in data.keys():
                page_number = int(data["page_number"])
            
            # select_result = method_stored.get_course(word=word,page_id=page_id,page_number=page_number)
            select_result = method_stored.get_chapter(course_id,word,page_id,page_number)
            
            
            check_list =[]
            person_chapter_list=[]
            if phone!=None:
                person_result,check_number = method_stored.get_person_chapter(phone)
                
                for one_result in person_result:
                    person_chapter_list.append(one_result["chapter_id"])

                    if one_result["checked"] ==1:
                        check_list.append(one_result["chapter_id"])
            if select_result!=None and select_result!=() and select_result!=[]:
                for one_result in select_result:
                    if one_result["id"] in check_list:
                        one_result["checked"] = 1
                    if one_result["id"] in person_chapter_list:
                        one_result["is_buy"] = 1


            result["data"]["product_list"] = select_result
            result["data"]["page_id"] = page_id
            result["data"]["page_number"] = page_number
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)


#用户信息更新
class product_info(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}


        try:
            phone =None
            try:
                #获取校验
                head = self.request.headers
                Authorization = head.get('Authorization', None)
                if type(Authorization) == list:
                    Authorization = Authorization[0]
                msg,status,phone = method_stored.check_auth(Authorization)
            except Exception as e:
                pass

            course_id = data["course_id"]
            
            select_result = method_stored.course_by_id(course_id)


            if select_result!="" and select_result!=None and select_result!=() and len(select_result)>0:
                try:
                    # 获取个人的数据
                    if phone != None:
                        person_result, check_number = method_stored.get_person_chapter(phone)

                        select_result[0]["learn_number"] = check_number
                        if person_result != () and person_result != None and person_result != [] and len(
                                person_result) > 0:
                            if course_id == person_result[0]["course_id"]:
                                select_result[0]["is_buy"] = 1
                except Exception as e:
                    pass

                if "date" in select_result[0].keys():
                    select_result[0]["date"] = select_result[0]["date"].strftime('%Y-%m-%d')
                result["data"]["course"] = select_result[0]
                msg="成功"
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                msg="获取课程失败"
                result["msg"] = msg

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass
        # print(result)
        self.write(result)


#用户信息更新
class chapter_info(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        try:
            phone=None
            try:
                #获取校验
                head = self.request.headers
                Authorization = head.get('Authorization', None)
                if type(Authorization) == list:
                    Authorization = Authorization[0]
                msg,status,phone = method_stored.check_auth(Authorization)
            except Exception as e:
                pass
            

            chapter_id = data["chapter_id"]
            course_id = data["course_id"]
            select_result = method_stored.chapter_by_id(chapter_id,course_id,phone)
            if select_result!="" and select_result!=None and select_result!=() and len(select_result)>0:
                chapter_number = method_stored.search_chapter_collect(chapter_id,course_id)
                select_result[0]["collect_number"] = chapter_number

                if "date" in select_result[0].keys():
                    select_result[0]["date"] = select_result[0]["date"].strftime('%Y-%m-%d')
                result["data"]["course"] = select_result[0]
                msg="成功"
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                msg="获取课程失败"
                result["msg"] = msg

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass
        # print(result)
        self.write(result)


#用户信息更新
class chapter_welfare(BaseHandler):

    def get(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        # data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        try:

            # chapter_id = data["chapter_id"]
            select_result = method_stored.chapter_by_welfare()
            if select_result!="" and select_result!=None and select_result!=() and len(select_result)>0:
                if "date" in select_result[0].keys():
                    select_result[0]["date"] = select_result[0]["date"].strftime('%Y-%m-%d')
                result["data"]["course"] = select_result[0]
                msg="成功"
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                msg="获取课程失败"
                result["msg"] = msg

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass
        # print(result)
        self.write(result)

class course_refund(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            #获取校验
            head = self.request.headers
            Authorization = head.get('Authorization', None)
            if type(Authorization) == list:
                Authorization = Authorization[0]
            msg,status,phone = method_stored.check_auth(Authorization)
            if not status:
                result["msg"] = msg
                return self.write(result)

            
            course_id = data["course_id"]
            
            #获取手机号
            # phone = data["phone"]
            if not phone:
                result["msg"] = "手机号获取失败"
                return self.write(result)


            msg,status =  method_stored.my_refund(course_id,phone)
            
            if status:
                msg="成功"
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                result["msg"] = "未查到记录"
            
        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)

#图片上传
class image_upload(BaseHandler):
 
    #获取表单内容
    def post(self,*args,**kwargs):
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}
        try:
            #获取表单中的数据，images就是对应的html中name值
            image=self.request.files['images']
            #得到一系列的数据，获取你想要的内容
            for imag in image:
                #图片文件名
                filename=imag.get('filename')
                #图片被转换后的字节内容
                body=imag.get('body')
                #获取的content_type
                content_type=imag.get('content_type')
 
                #获取绝对路径
                dir=os.path.join(os.getcwd(),'image',filename)
                #写入到文件目录中
                with open(dir,'wb')  as fw:
                    fw.write(body)
                
                result["code"] = 200
                result["msg"] = "success"
                result["success"] = True

        except Exception as e:
            pass
        
        self.write(result)


class image_read(BaseHandler):

    def get(self, *args, **kwargs):
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        try:
            msg="fail"
            imagename = self.get_argument('image')
            # imagename = "课程头图.jpg"
            if imagename.endswith('.jpg'):

                with open(r'image/{}'.format(imagename), 'rb') as f:
                    image = f.read()
                    # self.render(image)
                    self.write(image)
                    return self.set_header("Content-type", "image/jpg")
                
        except Exception as e:
            msg=e
            result["msg"] = msg
            pass
        
        self.write(result)

#留言记录
class write_person_note(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            #获取校验
            head = self.request.headers
            Authorization = head.get('Authorization', None)
            if type(Authorization) == list:
                Authorization = Authorization[0]
            msg,status,phone = method_stored.check_auth(Authorization)
            if not status:
                result["msg"] = msg
                return self.write(result)


            #获取手机号
            # phone = data["phone"]
            # if not phone:
            #     result["msg"] = "手机号获取失败"
            #     return self.write(result)
            # update_result,status = method_stored.update_person_info(data,str(phone))
            one_data = {}
            one_data["word"] = data["word"]
            one_data["nick_name"] = data["nick_name"]
            one_data["couse_id"] = data["course_id"]
            if "chapter_id" in data.keys():
                one_data["chapter_id"] = data["chapter_id"]
            now_day = datetime.datetime.now().strftime('%Y-%m-%d')
            one_data["date"] = now_day
            status = method_stored.insert_comment(one_data)
            if status:
                msg="成功"
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                msg="获取失败"
                result["msg"] = msg

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)


#留言记录
class get_person_note(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            #获取校验
            head = self.request.headers
            Authorization = head.get('Authorization', None)
            if type(Authorization) == list:
                Authorization = Authorization[0]
            msg,status,phone = method_stored.check_auth(Authorization)
            if not status:
                result["msg"] = msg
                return self.write(result)


            #获取手机号
            # phone = data["phone"]
            # if not phone:
            #     result["msg"] = "手机号获取失败"
            #     return self.write(result)
            # update_result,status = method_stored.update_person_info(data,str(phone))
            one_data = {}
            one_data["couse_id"] = data["course_id"]
            if "chapter_id" in data.keys():
                one_data["chapter_id"] = data["chapter_id"]

            status,select_result = method_stored.get_comment(one_data)
            
            if status:
                msg="成功"
                result["data"]["comments"] = select_result
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                msg="获取失败"
                result["msg"] = msg

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)

#留言记录
class get_image_icon(BaseHandler):

    def get(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        # data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:

            image_list,nav_icon_list = method_stored.get_icon()
            msg="成功"
            result["data"]["icon"] = image_list
            result["data"]["nav_icon"] = nav_icon_list
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)



#留言记录
class get_lunbo_image(BaseHandler):

    def get(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        # data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            image_list = method_stored.get_lunbo()
            msg="成功"
            result["data"]["image"] = image_list
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)


class chapter_check(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            #获取校验
            head = self.request.headers
            Authorization = head.get('Authorization', None)
            if type(Authorization) == list:
                Authorization = Authorization[0]
            msg,status,phone = method_stored.check_auth(Authorization)
            if not status:
                result["msg"] = msg
                return self.write(result)

            #获取手机号
            # phone = data["phone"]
            if not phone:
                result["msg"] = "手机号获取失败"
                return self.write(result)
            chapter_id = data["chapter_id"]
            course_id = data["course_id"]


            method_stored.get_chapter_check(phone,chapter_id,course_id)
            

            # result["data"]["courses"] = course_list

            # result["data"]["date"] = in_time
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)


class chapter_collect(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            #获取校验
            head = self.request.headers
            Authorization = head.get('Authorization', None)
            if type(Authorization) == list:
                Authorization = Authorization[0]
            msg,status,phone = method_stored.check_auth(Authorization)
            if not status:
                result["msg"] = msg
                return self.write(result)

            #获取手机号
            # phone = data["phone"]
            if not phone:
                result["msg"] = "手机号获取失败"
                return self.write(result)
            chapter_id = data["chapter_id"]
            course_id = data["course_id"]


            method_stored.get_chapter_collect(phone,chapter_id,course_id)
            
            # result["data"]["date"] = in_time
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)

class chapter_collect_number(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = {}
        try:
            data = tornado.escape.json_decode(self.request.body)
        except Exception as e:
            pass

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:

            chapter_id = data["chapter_id"]
            course_id = data["course_id"]


            chapter_number =method_stored.search_chapter_collect(chapter_id,course_id)
            
            # result["data"]["date"] = in_time
            msg="成功"
            result["data"]["chapter_number"]=chapter_number
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)

class PictureHandler(BaseHandler):
    def get(self):
        source_path = r'image'
        id = self.get_argument('id')
        if id.endswith('.jpg'):
            pic = open(source_path + r'/' + id, 'rb')
            pics = pic.read()
            self.write(pics)
            self.set_header("Content-type", "image/png")


application = tornado.web.Application([
    (r"/api/zhiku/login", login),
    (r"/api/zhiku/my_buy", my_buy),
    (r"/api/zhiku/person_info_update", person_info_update),
    (r"/api/zhiku/person_info", get_person_info),
    (r"/api/zhiku/person_card_update", person_card_update),
    (r"/api/zhiku/person_card", get_person_card),
    
    # (r"/api/zhiku/product_list", product_search),
    (r"/api/zhiku/product_search", product_search),
    (r"/api/zhiku/product_hot", product_hot),
    (r"/api/zhiku/chapter_search", chapter_search),
    (r"/api/zhiku/product_info", product_info),
    (r"/api/zhiku/course_refund", course_refund),
    ("/api/zhiku/image_upload",image_upload),
    ("/api/zhiku/image_read",image_read),
    ("/api/zhiku/pic",PictureHandler),
    ("/api/zhiku/icon",get_image_icon),
    ("/api/zhiku/lunbo_image",get_lunbo_image),
    (r"/api/zhiku/chapter_info",chapter_info),
    (r"/api/zhiku/welfare",chapter_welfare),
    (r"/api/zhiku/chapter_check",chapter_check),
    (r"/api/zhiku/chapter_collect",chapter_collect),
    (r"/api/zhiku/chapter_collect_number",chapter_collect_number)
    
])

# 问题
if __name__ == '__main__':
    # threading.Thread(target=get_pid.main2,).start()
    # 将socket对象添加到select或epoll中
    application.listen(8222)
    # 3. 将select或epoll开始死循环 While True:
    tornado.ioloop.IOLoop.instance().start()

















































